<template>
    <div class="roleManagement-list-page">
        <Row>
            <Col :xs="24">
                <Button type="primary" @click="handleAddRole" class='add' style="width:51px;height:35px;">             
                    <i class = "iconfont icon-add"></i>
                </Button>  
                <div class="margin-up-down">
                    <Input class="input" v-model.trim="filterObj.params.name" placeholder="角色名称"></Input>
                </div>
                <div class="margin-up-down">
                    <Button style="width:51px;height:35px;" type="primary" class='btnwid' @click="handleSearch"><i class = "iconfont icon-chaxun"></i></Button>
                </div>
            </Col>
        </Row>
        <div class="table">
            <Table
                size="small"
                :columns="columns"
                :data="tableData"
                @on-selection-change="selectChange"
                :loading="tableLoading"
                no-data-text="未查询到符合条件的记录"
                stripe
            ></Table>
            <div class="page">
                <Page :total="count" @on-change="loadPage" show-total show-elevator/>
            </div>
            <!-- 编辑/查看/新建弹窗 -->
            <Modal
                v-model="showRoleModal" width="500"  mask='false'  @on-cancel="() => {}" @on-visible-change="triggerVisibleChange" class="storeSystemManagement-roleManagement-list-MedicalModal">
                <p slot="header">
                    <span class='span'>{{{add: '添加角色', edit: '配置权限'}[modalType]}}</span>
                </p>
                <div class="body">
                    <Form ref="formInline" :model="formData"  label-position="right" :label-width="90">
                        <FormItem label="角色类型：" prop="type" :rules="[{ required: true, message: '请选择角色类型', type: 'number', trigger: 'change' }]">
                            <div v-if="modalType === 'edit'" class='xoverflow'>
                                <span>{{['', '药师', '药店工作人员'][formData.type]}}</span>
                            </div>
                            <template v-else>
                                <RadioGroup v-model="formData.type">
                                    <Radio :label="1">药师</Radio>
                                    <Radio :label="2">药店工作人员</Radio>
                                </RadioGroup>
                            </template>
                        </FormItem>
                        <FormItem label="角色名称：" prop="name" :rules="[{ required: true, message: '请输入角色名称', trigger: 'change' }]">
                            <div v-if="modalType === 'edit'" class='xoverflow'>
                                <span>{{formData.name}}</span>
                            </div>
                            <template v-else>
                                <Input v-model="formData.name" clearable placeholder="请输入角色名称" />
                            </template>
                        </FormItem>
                        <FormItem label="角色编码：" prop="code" :rules="[{ required: true, message: '请输入角色编码', trigger: 'change' }]">
                            <div v-if="modalType === 'edit'" class='xoverflow'>
                                <span>{{formData.code}}</span>
                            </div>
                            <template v-else>
                                <Input v-model="formData.code" clearable placeholder="药师类角色编码规则doctor_xxxx" />
                            </template>
                        </FormItem>
                    </Form>
                    <div class="tree-wrapper">
                        <label>配置权限：</label>
                        <div class="tree-scroll-wrapper spin-container">
                            <Tree :data="treeData" ref="tree" show-checkbox multiple></Tree>
                            <Spin size="large" fix v-if="showTreeloading"></Spin>
                        </div>
                    </div>
                </div>
                <div class="btn-group">
                    <Button style="width:75px;height:35px;" class="save" type="primary" :loading="showSaveBtnloading" @click="handleSave">保存</Button>
                    <Button style="width:75px;height:35px;"
                        class="close"
                        @click="() => {showRoleModal = false; $refs['formInline'].resetFields()}"
                    >关闭</Button>
                </div>
            </Modal>
            <!-- 删除确认弹窗 -->
            <Modal v-model="showDelConfirmModal" title="删除对照结果" class="pharmacyregister-list-delModal">
                <div class="content">
                    <p class="tip">确定删除<span class="hospitalName">{{curRecord.name}}</span>吗？</p>
                    <p class="zhu">注：删除后无法恢复。</p>
                    <div slot="footer">
                        <div class="btn-group">
                            <Button style="width:75px;height:35px;" class="left btn" type="primary" :loading="delBtnLoading" @click="handleDel">确认删除</Button>
                            <Button style="width:75px;height:35px;" class="right btn" @click="showDelConfirmModal = false">取消</Button>
                        </div>
                    </div>
                </div>
            </Modal>
        </div>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import { Page } from "view-design";
const formData = {
    name: null, //药品编码
    type: null,
    code: null,
}
export default {
    data() {
        return {
            filterObj: {
                pageNo: 1,
                pageSize: 10,
                params: {
                name: '',
                }
            },
            count: 0,
            columns: [
                { type: "sum", title: "序号", width: 60, align: "center",
                    render: (h, params) => {
                        let sum = (this.filterObj.pageNo-1)*this.filterObj.pageSize + params.index +1;
                        return h("span", sum);
                    }
                },
                { title: "角色名称", key: "name", align: "center" },
                { title: "创建时间", key: "createTime", align: "center" },
                { title: "创建人", key: "createName", align: "center" },
                {
                title: "设置",
                key: "iOperate",
                width: 200,
                render: (h, params) => {
                    return h("div", [
                    h(
                        "Button",
                        {
                        props: {
                            type: "primary",
                            size: "small"
                        },
                        style: {
                            margin: "0px 6px"
                        },
                        on: {
                            click: () => {
                            this.handleEdit(params);
                            }
                        }
                        },
                        "配置权限"
                    ),
                    h(
                        "Button",
                        {
                        props: {
                            type: "error",
                            size: "small"
                        },
                        style: {
                            margin: "0px 6px",
                            color:"#fff"
                        },
                        on: {
                            click: () => {
                            this.handleRemove(params);
                            }
                        }
                        },
                        "删除"
                    )
                    ]);
                }
                }
            ],
            tableData: [],
            tableLoading: false,
            showRoleModal: false,
            showTreeloading: false,
            showSaveBtnloading: false,
            modalType: null, 
            formData: this.deepClone(formData),
            treeData: [],
            curRecord: {},
            showDelConfirmModal: false,
            delBtnLoading: false,
        };
    },
    created() {
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "",
                title: "药店端账号权限配置"
            },
            {
                path: "/index/maintain/storeSystemManagement/roleManagement/list",
                title: "药店端药店端角色权限管理"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted() {
        this.storeManagementRolePage();
    },
    methods: {
        loadPage(index) {
            this.filterObj.pageNo = index;
            this.storeManagementRolePage();
        },
        handleDel() {
            this.storeManagementRoleDelete(this.curRecord);
        },
        handleSearch() {
            this.filterObj.pageNo = 1;
            this.storeManagementRolePage();
        },
        handleAddRole() {
            this.modalType = "add";
            this.showRoleModal = true;
            this.storeManagementRoleMenus(-1);
        },
        handleRemove(record) {
            this.curRecord = record.row;
            this.showDelConfirmModal = true;
        },
        handleEdit(record) {
            console.log('aaa')
            this.modalType = "edit";
            this.showRoleModal = true;
            this.curRecord = record.row;
            this.storeManagementRoleDetail(record.row.id);
            this.storeManagementRoleMenus(record.row.id);
        },
        triggerVisibleChange(status) {
            if (!status) {
                this.formData = this.deepClone(formData);
            }
        },
        formatTreeData(data = []) {
            var treeData = [];
            for (var i = 0; i < data.length; i++) {
                const {id, name, checked,children} = data[i];
                if (!children || !children.length) {
                    treeData.push({
                        title: name,
                        id,
                        checked, 
                        children: []
                    })
                } else {
                    treeData.push({
                        title: name,
                        id,
                        checked,
                        children: this.formatTreeData(children)
                    })
                }
            }
            return treeData;
        },
        handleSave() {
            this.$refs['formInline'].validate((valid) => {
                if (valid) {
                    if (this.modalType === 'add') {
                        this.storeManagementRoleCreate();
                    } else if (this.modalType === 'edit') {
                        this.storeManagementRoleUpdate();
                    }
                }
            })
        },
        storeManagementRolePage() {
            this.tableLoading = true;
            let body={
                pageNo:this.filterObj.pageNo,
                pageSize:this.filterObj.pageSize,
                searchKey:this.filterObj.params.name?this.filterObj.params.name:''
            }
            const reqObj = JSON.parse(JSON.stringify(this.filterObj));
            // 处理筛选条件
            reqObj.params.name && (reqObj.params.name_LIKE = reqObj.params.name);
            delete reqObj.params.name
            this.$axios
                .post(api.storeManagementRolePage, body)
                .then(res => {
                    if (res.data.code !== 1) {
                        this.$Message.error(res.data.message);
                    } else {
                        this.tableData = res.data.object.records;
                        this.count = res.data.object.total;
                    }
                    this.tableLoading = false;
                })
                .catch(res => {
                    this.tableLoading = false;
                });
        },
        storeManagementRoleDetail(id) {
            console.log(api.storeManagementRoleDetail.replace(/{id}/, id))
            this.$axios
                .post(api.storeManagementRoleDetail.replace(/{id}/, id),{})
                .then(res => {
                    console.log(res.data.code)
                    if (res.data.code !== 1) {
                        this.$Message.error(res.data.message);
                    } else {
                        this.formData = {
                        name: res.data.object.name,
                        code: res.data.object.code,
                        type: res.data.object.type,
                        }
                    }
                })
                .catch(res => {
                    console.log('fas')
                });
        },
        storeManagementRoleMenus(id) {
            this.treeData = [];
            this.showTreeloading = true;
            this.$axios
                .post(api.storeManagementRoleMenus.replace(/{id}/, id),{})
                .then(res => {
                    if (res.data.code !== 1) {
                        this.$Message.error(res.data.message);
                    } else {
                        this.treeData = this.formatTreeData(res.data.object);
                    }
                    this.showTreeloading = false;
                })
                .catch(res => {
                    this.showTreeloading = false;
                });
        },
        storeManagementRoleDelete(formData) {
            this.delBtnLoading = true;
            const params = {
                name: formData.name,
                type: formData.type,
                code: formData.code,
                createName: formData.createName,
                createTime: formData.createTime,
                id: formData.id,
            };
            this.$axios
                .post(api.storeManagementRoleDelete,params)
                .then(res => {
                    if (res.data.code !== 1) {
                        this.$Message.error(res.data.message);
                    } else {
                        this.$Message.success('删除成功');
                        this.showDelConfirmModal = false;
                        this.storeManagementRolePage();
                    }
                    this.delBtnLoading = false;
                })
                .catch(res => {
                    this.delBtnLoading = false;
                });
        },
        storeManagementRoleCreate() {
            const params = {
                name: this.formData.name,
                type: this.formData.type,
                code: this.formData.code,
                menuIds: this.$refs['tree'].getCheckedNodes().map(item => item.id),
            };
            this.showSaveBtnloading = true;
            this.$axios
                .post(api.storeManagementRoleCreate, params)
                .then(res => {
                    if (res.data.code !== 1) {
                        this.$Message.error(res.data.message);
                    } else {
                        this.$Message.success('添加成功');
                        this.showRoleModal = false;
                        this.storeManagementRolePage();
                    }
                    this.showSaveBtnloading = false;
                })
                .catch(res => {
                    this.showSaveBtnloading = false;
                });
        },
        storeManagementRoleUpdate() {
            const params = {
                id: this.curRecord.id,
                type: this.formData.type,
                name: this.formData.name,
                code: this.formData.code,
                menuIds: this.$refs['tree'].getCheckedNodes().map(item => item.id)
            };
            this.showSaveBtnloading = true;
            this.$axios
            .post(api.storeManagementRoleUpdate, params)
            .then(res => {
                if (res.data.code !== 1) {
                    this.$Message.error(res.data.message);
                } else {
                    this.$Message.success(res.data.message);
                    this.showRoleModal = false;
                    this.storeManagementRolePage();
                }
                this.showSaveBtnloading = false;
            })
            .catch(res => {
                this.showSaveBtnloading = false;
            });
        },
        deepClone(obj) {
            return JSON.parse(JSON.stringify(obj));
        }
    },
    watch: {
        'filterObj.pageSize'(nv, ov) {
            this.filterObj.pageNo = 1;
            this.storeManagementRolePage();
        },
        treeData(n) {
        },
        showRoleModal() {
            this.$refs['formInline'].resetFields();
        }
    }
};
</script>
<style scoped lang="less">
.add{
    background:#21c780;
    border:none;
    outline:none;
    i{
        font-size:14px;
    }
}
.roleManagement-list-page {
    margin-left: 1%;
    padding: 10px;
    width: 98%;
    background: #ffffff;
    box-sizing: border-box;
    .margin-up-down {
        display: inline-block;
        margin-top: 10px;
        margin-bottom: 20px;
        Button{display: inline-block;}
        .btnwid{
            width:60px;
            font-size:14px;margin-right:5px;padding:0
            i{
                font-size:24px;
            }
        }
    }
    .xoverflow{
        overflow-x:auto !!important;
    }
    .oright{
        float:right !important;
    }
    header {
        margin-bottom: 10px;
        position: relative;
        .filter-part {
            display: flex;
            flex-wrap: wrap;
            .filter-item {
                display: flex;
                margin: 10px 10px 10px 0;
                label {
                white-space: nowrap;
                line-height: 32px;
                text-align: right;
                }
                .input {
                    width: 220px !important;
                }
                .select {
                width: 70px;
                }
            }
            .filter-btn-group {
                margin: 10px 10px 10px 0;
                flex: 0 0 auto;
            }
        }
        .fun-part {
            position: absolute;
            top: 10px;
            right: 0;
            a {
                vertical-align: bottom;
            }
        }
    }
    .page{
        text-align: center;
        margin:5px 0;
    }
}
.storeSystemManagement-roleManagement-list-MedicalModal {
    .span{
        padding-left:20px;
    }
    .body {
        // box-shadow: 10px 0px 3px #888888;
        padding-right: 40px;
        .tree-wrapper {
            display: flex;
            label {
                width: 90px;
                text-align: right;
            }
            .tree-scroll-wrapper {
                flex: 1 1 auto;
                height: 300px;
                border: 1px solid #dddee1;
                padding: 10px;
                overflow: auto;
            }
        }
    }
    /deep/ .ivu-modal-wrap {
        .ivu-modal{
            float:right !important;
        }
        label.ivu-form-item-label {
            padding-right: 0;
        }
        .ivu-modal-content{
            box-shadow: 8px -5px 3px #7581e7; 
        }
        .ivu-modal-footer {
            display: none;
        }
        .btn-group {
            margin-top: 30px;
            margin-bottom: 10px;
            text-align: center;
            .save {
                width: 100px;
                margin-right: 20px;
            }
            .close {
                margin-left: 20px;
                width: 100px;
            }
        }
    }
}
.spin-container{
    display: inline-block;
    width: 200px;
    height: 100px;
    position: relative;
    border: 1px solid #eee;
}
.pharmacyregister-list-delModal {
    /deep/ .ivu-modal-wrap {
        .ivu-modal-content{
            border:1px solid  #7581e7;
        }
        .ivu-modal-footer {
            display: none;
        }
        .btn-group {
            padding-top: 20px;
            text-align: center;
            .left {
                margin-right: 20px;
            }
            .right {
                margin-left: 20px;
            }
        }
        .content {
            text-align: center;
            .tip {
                padding-bottom: 10px;
                .hospitalName {
                    color: rgb(253, 120, 58);
                }
            }
        }
    }
}
</style>